package cn.manyufun.myf.ui.user.model;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.manyufun.myf.api.Api;
import cn.manyufun.myf.api.HostType;
import cn.manyufun.myf.app.AppApplication;
import cn.manyufun.myf.bean.RegisterBean;
import cn.manyufun.myf.bean.VerifyCodeBean;
import cn.manyufun.myf.common.base.BaseModel;
import cn.manyufun.myf.common.baserx.RxSchedulers;
import cn.manyufun.myf.common.commonutils.RSAUtils;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import rx.Observable;

import static cn.manyufun.myf.common.commonutils.VersionUtils.getVersionCode;

/**
 * Created by Xiao on 2018-02-24.
 */

public class RegisterModel implements BaseModel {
    public Observable<VerifyCodeBean> sendVerifyCode(String phone) {
        JSONObject root = new JSONObject();
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String t = format.format(new Date());
            root.put("AppVersion", getVersionCode(AppApplication.getAppContext()));
            root.put("DeviceID", "android");
            root.put("Key", t);
            root.put("Token", RSAUtils.md5(t + "MYF"));
            root.put("Phone", phone);
            root.put("ActionType", 1);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), root.toString());
        return Api.getDefault(HostType.manyufun).sendCode(requestBody)
                .compose(RxSchedulers.<VerifyCodeBean>io_main());

    }

    public Observable<RegisterBean> requestRegister(String username, String pwd, String verifyCode) {
        JSONObject root = new JSONObject();
        try {
            root.put("AppVersion", getVersionCode(AppApplication.getAppContext()));
            root.put("DeviceID", "android");
            root.put("UserName", username);
            root.put("Phone", username);
            root.put("VerifyCode", verifyCode);
            root.put("Pwd", pwd);
            root.put("HeadImgUrl", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), root.toString());
        return Api.getDefault(HostType.manyufun).register(requestBody)
                .compose(RxSchedulers.<RegisterBean>io_main());
    }
}
